package com.briup.estore.service.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.briup.estore.bean.Customer;
import com.briup.estore.mapper.ICustomerMapper;
import com.briup.estore.result.Res;
import com.briup.estore.result.Result;
import com.briup.estore.service.ICustomerService;
import com.briup.estore.utils.ExtUtils;

@Service
public class CustomerServiceImpl implements ICustomerService {

	@Autowired
	private ICustomerMapper customerMapper;

	@Override
	@Transactional
	public Result registerCustomer(Customer customer) throws Exception {
		Result result = Res.success("注册成功！");
		List<String> checkList = ExtUtils.checkCustomer(customer);
		if (checkList != null) {
			switch (checkList.get(0)) {
			case "name":
				result = Res.failure("用户名为空！");
				break;
			case "pwd":
				result = Res.failure("密码为空！");
				break;
			case "zipcode":
				result = Res.failure("邮编为空！");
				break;
			case "telephone":
				result = Res.failure("电话为空！");
				break;
			case "email":
				result = Res.failure("邮箱为空！");
				break;
			default:
				result = Res.failure("未知异常！");
				break;
			}
			return result;
		}

		Customer cus = customerMapper.findCustomerByName(customer);
		if (cus != null) {
			return Res.failure("该用户已被注册！");
		}

		customer.setPwd(ExtUtils.ExtMD5(customer));
		int i = customerMapper.insertCustomer(customer);
		if (i > 0) {
			return result;
		} else {
			return Res.failure("未知错误，注册失败！");
		}

	}

	@Override
	public Result loginCustomer(Customer customer) throws Exception {
		if (StringUtils.isEmpty(customer.getName()) || StringUtils.isEmpty(customer.getPwd())) {
			return Res.failure("用户名或密码为空！");
		}
		Customer cus = customerMapper.findCustomerByName(customer);
		if (cus != null) {
			if (cus.getPwd().equals(ExtUtils.ExtMD5(customer))) {
				return Res.success(cus, "登录成功！");
			}
			return Res.failure("密码错误！");
		}

		return Res.failure("用户未注册，请先注册！");
	}

}
